package com.jacklin.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 设置token到cookie
 * @Author 林必昭
 * @Date 2019/4/13 15:55
 */
public class CookieUtil {

    public static  void set(HttpServletResponse response,String name,String value,int maAge){

        Cookie cookie = new Cookie(name,value);
        cookie.setPath("/");
        cookie.setMaxAge(7200);
        response.addCookie(cookie);

    }

    /**
     * 获取cookie
     * @param request
     * @param name
     */
    public static Cookie get(HttpServletRequest request,String name){

        Map<String, Object> cookieMap = readCookieMap(request);
        if (cookieMap.containsKey(name)){
            return (Cookie) cookieMap.get(name);
        }else {
            return null;
        }

    }

    /**
     * 获取cookie，先将cookie封装成Map形式存储到cookieMap中,方便在get方法中获取
     * @param request
     * @return
     */
    public static Map<String,Object> readCookieMap(HttpServletRequest request){

        Map<String,Object> cookieMap = new HashMap<>();
        Cookie[] cookies = request.getCookies();
        if (cookies!=null){
            for (Cookie cookie:cookies){
                cookieMap.put(cookie.getName(),cookie);
            }
        }
        return cookieMap;
    }
}
